<?php
/**
 * 地区模型
 * 对应表：oa_region
 * 标准省市区三级联动数据结构
 */

declare (strict_types = 1);

namespace app\model\system;

use think\Model;

class Region extends Model
{
    /**
     * 设置当前模型对应的完整数据表名称
     * 注意：由于数据库配置了表前缀'oa_'，这里使用完整表名避免重复前缀
     */
    protected $name = 'region';
    
    /**
     * 关闭自动时间戳
     * oa_region表没有create_time和update_time字段
     */
    protected $autoWriteTimestamp = false;
    
    /**
     * 设置字段信息
     */
    protected $schema = [
        'id'         => 'int',
        'parent_id'  => 'int',
        'level'      => 'int',
        'name'       => 'string',
        'sort'       => 'int',
        'status'     => 'int',
        'initial'    => 'string',
        'pinyin'     => 'string',
        'citycode'   => 'string',
        'adcode'     => 'string',
        'lng_lat'    => 'string',
    ];
    
    /**
     * 类型转换
     */
    protected $type = [
        'id'        => 'integer',
        'parent_id' => 'integer',
        'level'     => 'integer',
        'name'      => 'string',
        'sort'      => 'integer',
        'status'    => 'integer',
        'initial'   => 'string',
        'pinyin'    => 'string',
        'citycode'  => 'string',
        'adcode'    => 'string',
        'lng_lat'   => 'string',
    ];
    
    /**
     * 获取子地区
     */
    public function children()
    {
        return $this->hasMany(Region::class, 'parent_id', 'id');
    }
    
    /**
     * 获取父地区
     */
    public function parent()
    {
        return $this->belongsTo(Region::class, 'parent_id', 'id');
    }
    
    /**
     * 获取子地区数量
     */
    public function getChildCount(): int
    {
        return $this->where('parent_id', $this->id)->count();
    }
    
    /**
     * 是否有子地区
     */
    public function hasChildren(): bool
    {
        return $this->getChildCount() > 0;
    }
    
    /**
     * 根据父级ID获取子地区列表
     */
    public static function getChildrenByParentId(int $parentId = 0)
    {
        return self::where('parent_id', $parentId)
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 根据层级获取地区列表
     */
    public static function getByLevel(int $level)
    {
        return self::where('level', $level)
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 获取完整地址路径
     */
    public function getFullAddress(): string
    {
        $address = [];
        $current = $this;
        
        while ($current && $current->parent_id > 0) {
            array_unshift($address, $current->name);
            $current = $current->parent;
        }
        
        if ($current) {
            array_unshift($address, $current->name);
        }
        
        return implode(' ', $address);
    }
    
    /**
     * 根据名称模糊搜索地区
     */
    public static function searchByName(string $keyword)
    {
        return self::where('name', 'like', "%{$keyword}%")
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 根据首字母获取地区
     */
    public static function getByInitial(string $initial)
    {
        return self::where('initial', $initial)
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 根据拼音搜索地区
     */
    public static function searchByPinyin(string $pinyin)
    {
        return self::where('pinyin', 'like', "%{$pinyin}%")
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 获取级联选择器数据
     */
    public static function getCascaderData()
    {
        // 获取所有省份（level=1）
        $provinces = self::where('level', 1)
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();
            
        $result = [];
        
        foreach ($provinces as $province) {
            $provinceData = [
                'value' => $province['id'],
                'label' => $province['name'],
                'children' => []
            ];
            
            // 获取该省份下的城市（level=2）
            $cities = self::where('parent_id', $province['id'])
                ->where('level', 2)
                ->where('status', 1)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select()
                ->toArray();
                
            foreach ($cities as $city) {
                $cityData = [
                    'value' => $city['id'],
                    'label' => $city['name'],
                    'children' => []
                ];
                
                // 获取该城市下的区县（level=3）
                $districts = self::where('parent_id', $city['id'])
                    ->where('level', 3)
                    ->where('status', 1)
                    ->order('sort', 'asc')
                    ->order('id', 'asc')
                    ->select()
                    ->toArray();
                    
                foreach ($districts as $district) {
                    $cityData['children'][] = [
                        'value' => $district['id'],
                        'label' => $district['name']
                    ];
                }
                
                $provinceData['children'][] = $cityData;
            }
            
            $result[] = $provinceData;
        }
        
        return $result;
    }
    
    /**
     * 获取完整树形结构（支持4级）
     */
    public static function getTreeData(int $maxLevel = 4)
    {
        // 获取所有启用的地区
        $regions = self::where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();
            
        // 构建树形结构
        $tree = [];
        $map = [];
        
        foreach ($regions as $region) {
            $map[$region['id']] = [
                'value' => $region['id'],
                'label' => $region['name'],
                'level' => $region['level'],
                'parent_id' => $region['parent_id'],
                'initial' => $region['initial'],
                'pinyin' => $region['pinyin'],
                'citycode' => $region['citycode'],
                'adcode' => $region['adcode'],
                'lng_lat' => $region['lng_lat'],
                'children' => []
            ];
        }
        
        foreach ($map as $id => &$node) {
            if ($node['parent_id'] == 0) {
                $tree[] = &$node;
            } else if (isset($map[$node['parent_id']]) && $node['level'] <= $maxLevel) {
                $map[$node['parent_id']]['children'][] = &$node;
            }
        }
        
        return $tree;
    }
    
    /**
     * 只获取启用的地区
     */
    public function scopeEnable($query)
    {
        return $query->where('status', 1);
    }
    
    /**
     * 根据状态获取地区
     */
    public static function getByStatus(int $status = 1)
    {
        return self::where('status', $status)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }
    
    /**
     * 根据区域编码获取地区
     */
    public static function getByAdcode(string $adcode)
    {
        return self::where('adcode', $adcode)
            ->where('status', 1)
            ->find();
    }
    
    /**
     * 根据城市编码获取地区
     */
    public static function getByCitycode(string $citycode)
    {
        return self::where('citycode', $citycode)
            ->where('status', 1)
            ->find();
    }
}